<template>
  <div class="home-container">
    <!-- 欢迎卡片 -->
    <el-card class="welcome-card">
      <div class="welcome-content">
        <div class="welcome-text">
          <h2>欢迎回来，管理员</h2>
          <p>今天是 {{ currentDate }}，祝您工作愉快！</p>
        </div>
        <div class="welcome-stats">
          <div class="stat-item">
            <el-icon><DataLine /></el-icon>
            <div class="stat-info">
              <span class="stat-value">1,234</span>
              <span class="stat-label">总访问量</span>
            </div>
          </div>
          <div class="stat-item">
            <el-icon><Document /></el-icon>
            <div class="stat-info">
              <span class="stat-value">56</span>
              <span class="stat-label">待处理事项</span>
            </div>
          </div>
          <div class="stat-item">
            <el-icon><User /></el-icon>
            <div class="stat-info">
              <span class="stat-value">89</span>
              <span class="stat-label">活跃用户</span>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 数据卡片网格 -->
    <div class="data-grid">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-card class="data-card">
            <div class="data-card-header">
              <h3>系统状态</h3>
              <el-tag type="success">运行正常</el-tag>
            </div>
            <div class="data-card-content">
              <div class="status-item">
                <span>CPU使用率</span>
                <el-progress :percentage="45" :color="customColors"></el-progress>
              </div>
              <div class="status-item">
                <span>内存使用率</span>
                <el-progress :percentage="60" :color="customColors"></el-progress>
              </div>
              <div class="status-item">
                <span>磁盘使用率</span>
                <el-progress :percentage="30" :color="customColors"></el-progress>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="data-card">
            <div class="data-card-header">
              <h3>最近活动</h3>
              <el-button type="primary" link>查看全部</el-button>
            </div>
            <div class="activity-list">
              <div class="activity-item" v-for="(activity, index) in recentActivities" :key="index">
                <el-icon><component :is="activity.icon" /></el-icon>
                <div class="activity-info">
                  <span class="activity-text">{{ activity.text }}</span>
                  <span class="activity-time">{{ activity.time }}</span>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="data-card">
            <div class="data-card-header">
              <h3>快捷操作</h3>
            </div>
            <div class="quick-actions">
              <el-button type="primary">
                <el-icon><Plus /></el-icon>新建任务
              </el-button>
              <el-button type="success">
                <el-icon><Upload /></el-icon>上传文件
              </el-button>
              <el-button type="warning">
                <el-icon><Setting /></el-icon>系统设置
              </el-button>
              <el-button type="info">
                <el-icon><Document /></el-icon>查看报告
              </el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <el-row :gutter="20" class="chart-row">
      <el-col :span="16">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>数据趋势</span>
              <el-radio-group v-model="timeRange" size="small">
                <el-radio-button label="week">本周</el-radio-button>
                <el-radio-button label="month">本月</el-radio-button>
                <el-radio-button label="year">全年</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container">
            <v-chart class="chart" :option="lineChartOption" autoresize />
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>数据分布</span>
            </div>
          </template>
          <div class="chart-container">
            <v-chart class="chart" :option="pieChartOption" autoresize />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="table-row">
      <el-col :span="24">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>最近活动</span>
              <el-button type="primary" link>查看全部</el-button>
            </div>
          </template>
          <el-table :data="recentActivities" style="width: 100%">
            <el-table-column prop="time" label="时间" width="180" />
            <el-table-column prop="user" label="用户" width="120" />
            <el-table-column prop="action" label="操作" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.status === 'success' ? 'success' : 'danger'">
                  {{ scope.row.status === 'success' ? '成功' : '失败' }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, PieChart } from 'echarts/charts'
import {
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import {
  User,
  DataLine,
  Setting,
  Document,
  Plus,
  Upload,
  ArrowUp,
  ArrowDown
} from '@element-plus/icons-vue'
import axios from 'axios'

// 注册 ECharts 组件
use([
  CanvasRenderer,
  LineChart,
  PieChart,
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent
])

const currentDate = ref(new Date().toLocaleDateString())
const customColors = [
  {color: '#4CAF50', percentage: 60},
  {color: '#81C784', percentage: 80},
  {color: '#C8E6C9', percentage: 100}
]

const timeRange = ref('week')

// 折线图配置
const lineChartOption = ref({
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['用户增长', '数据增长']
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '用户增长',
      type: 'line',
      smooth: true,
      data: [120, 132, 101, 134, 90, 230, 210],
      itemStyle: {
        color: '#409EFF'
      }
    },
    {
      name: '数据增长',
      type: 'line',
      smooth: true,
      data: [220, 182, 191, 234, 290, 330, 310],
      itemStyle: {
        color: '#67C23A'
      }
    }
  ]
})

// 饼图配置
const pieChartOption = ref({
  tooltip: {
    trigger: 'item'
  },
  legend: {
    orient: 'vertical',
    left: 'left'
  },
  series: [
    {
      name: '数据分布',
      type: 'pie',
      radius: '50%',
      data: [
        { value: 1048, name: '用户数据' },
        { value: 735, name: '系统数据' },
        { value: 580, name: '文档数据' },
        { value: 484, name: '其他数据' }
      ],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }
  ]
})

const recentActivities = ref([
  {
    time: '2024-03-20 10:00:00',
    user: '张三',
    action: '添加了新用户',
    status: 'success'
  },
  {
    time: '2024-03-20 09:30:00',
    user: '李四',
    action: '更新了系统配置',
    status: 'success'
  },
  {
    time: '2024-03-20 09:00:00',
    user: '王五',
    action: '删除了数据记录',
    status: 'success'
  },
  {
    time: '2024-03-20 08:30:00',
    user: '赵六',
    action: '上传了文档',
    status: 'success'
  }
])

// 统计数据
const statistics = ref([
  {
    label: '总用户数',
    value: '0',
    icon: 'User',
    color: '#409EFF',
    trend: 0
  },
  {
    label: '数据总量',
    value: '0',
    icon: 'DataLine',
    color: '#67C23A',
    trend: 0
  },
  {
    label: '系统配置',
    value: '0',
    icon: 'Setting',
    color: '#E6A23C',
    trend: 0
  },
  {
    label: '文档数量',
    value: '0',
    icon: 'Document',
    color: '#F56C6C',
    trend: 0
  }
])

// 系统状态
const systemStatus = ref({
  cpu: 0,
  memory: 0,
  disk: 0
})

// 获取统计数据
const fetchStatistics = async () => {
  try {
    const response = await axios.get('/api/statistics')
    if (response.data.code === 200) {
      const data = response.data.data
      statistics.value = [
        {
          label: '总用户数',
          value: data.userCount.toLocaleString(),
          icon: 'User',
          color: '#409EFF',
          trend: data.userTrend
        },
        {
          label: '数据总量',
          value: data.dataCount.toLocaleString(),
          icon: 'DataLine',
          color: '#67C23A',
          trend: data.dataTrend
        },
        {
          label: '系统配置',
          value: data.configCount.toLocaleString(),
          icon: 'Setting',
          color: '#E6A23C',
          trend: data.configTrend
        },
        {
          label: '文档数量',
          value: data.documentCount.toLocaleString(),
          icon: 'Document',
          color: '#F56C6C',
          trend: data.documentTrend
        }
      ]
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 获取系统状态
const fetchSystemStatus = async () => {
  try {
    const response = await axios.get('/api/system/status')
    if (response.data.code === 200) {
      systemStatus.value = response.data.data
    }
  } catch (error) {
    console.error('获取系统状态失败:', error)
  }
}

// 获取图表数据
const fetchChartData = async () => {
  try {
    const response = await axios.get('/api/statistics/chart', {
      params: { timeRange: timeRange.value }
    })
    if (response.data.code === 200) {
      const data = response.data.data
      lineChartOption.value.xAxis.data = data.dates
      lineChartOption.value.series[0].data = data.userGrowth
      lineChartOption.value.series[1].data = data.dataGrowth
      
      pieChartOption.value.series[0].data = data.distribution
    }
  } catch (error) {
    console.error('获取图表数据失败:', error)
  }
}

// 获取最近活动
const fetchRecentActivities = async () => {
  try {
    const response = await axios.get('/api/activities/recent')
    if (response.data.code === 200) {
      recentActivities.value = response.data.data
    }
  } catch (error) {
    console.error('获取最近活动失败:', error)
  }
}

// 监听时间范围变化
watch(timeRange, () => {
  fetchChartData()
})

// 初始化
onMounted(() => {
  fetchStatistics()
  fetchSystemStatus()
  fetchChartData()
  fetchRecentActivities()
})
</script>

<style scoped>
.home-container {
  padding: 20px;
}

.welcome-card {
  margin-bottom: 20px;
}

.welcome-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.welcome-text h2 {
  margin: 0;
  color: #4CAF50;
  font-size: 24px;
}

.welcome-text p {
  margin: 10px 0 0;
  color: #666;
}

.welcome-stats {
  display: flex;
  gap: 30px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.stat-item .el-icon {
  font-size: 24px;
  color: #4CAF50;
}

.stat-info {
  display: flex;
  flex-direction: column;
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.data-grid {
  margin-top: 20px;
}

.data-card {
  height: 100%;
}

.data-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.data-card-header h3 {
  margin: 0;
  color: #333;
}

.status-item {
  margin-bottom: 15px;
}

.status-item span {
  display: block;
  margin-bottom: 5px;
  color: #666;
}

.activity-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.activity-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.activity-item .el-icon {
  color: #4CAF50;
  font-size: 18px;
}

.activity-info {
  display: flex;
  flex-direction: column;
}

.activity-text {
  color: #333;
}

.activity-time {
  font-size: 12px;
  color: #999;
}

.quick-actions {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
}

.quick-actions .el-button {
  width: 100%;
  margin: 0;
}

.quick-actions .el-icon {
  margin-right: 4px;
}

.chart-row {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  height: 300px;
}

.chart {
  height: 100%;
}

.table-row {
  margin-bottom: 20px;
}
</style> 